package com.banmao.learnandorid.listView;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.banmao.learnandorid.R;
import com.banmao.learnandorid.entity.AdapterPojo;

import java.util.List;

public class MyAdapter<T extends AdapterPojo> extends BaseAdapter {

    List<T> data;

    Context context;

    public MyAdapter(List<T> data, Context context) {
        this.data = data;
        this.context = context;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return data.get(i).getPk();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder;
        if(view == null) {
            // 对于每个Item，其布局是不变的，所以用view进行缓存
            // 这句的意义是用 list_item 这个布局对 context 传入的对象进行渲染
            view = LayoutInflater.from(context).inflate(R.layout.list_item, viewGroup, false);

            viewHolder = new ViewHolder();
            viewHolder.textView = view.findViewById(R.id.list_item);

            // 将 viewHolder 放入view中进行缓存
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.textView.setText(data.get(i).getText());
//        Log.e("listView", "print: " + textView.getText());

        return view;
    }

    // 缓存textView
    /**
     *  因为 getView 这个方法，每次显示该条目时就会执行一次
     *  而 findViewById 耗时，因此对View进行缓存
     */
    public class ViewHolder {
        TextView textView;
    }

}
